<template>
  <div>
    <div>
      <el-row :gutter="20">
        <div
          style="background-color: #fefefe; padding: 5px 5px 0px 5px;border-radius: 1px; border-bottom: 1px solid #EEEEEE; ">
          <el-row :gutter="20" style="line-height: 35px;">
            <el-col style="width: 300px;display: flex;">
              <div class="item_label">开票区间:</div>
              <el-date-picker type="daterange" v-model="filterData.daterange" size="mini" start-placeholder="起始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" range-separator="至"
                style="width: 100%;"></el-date-picker>
            </el-col>
            <el-col style="width: 200px;display: flex;">
              <div class="item_label">发票状态:</div>
              <el-select v-model="filterData.status" placeholder="发票状态" size="mini" clearable style="width: 100%;">
                <el-option label="正常" value="1"></el-option>
                <el-option label="作废" value="0"></el-option>
              </el-select>
            </el-col>

            <el-col style="width: 300px;display: flex;">
              <div class="item_label">发票类型:</div>
              <el-select v-model="filterData.type" placeholder="发票类型" size="mini" clearable style="width: 100%;">
                <el-option label="增值税普票" value="增值税普票"></el-option>
                <el-option label="增值税专票" value="增值税专票"></el-option>
              </el-select>
            </el-col>
            <el-col style="width: 300px;display: flex;">
              <div class="item_label">销项票号码:</div>
              <el-input v-model="filterData.fphm" style="width: 100%;" placeholder="销项数电票号码或纸质发票号码" size="mini"
                clearable></el-input>
            </el-col>

            <el-col style="width: 300px;display: flex;">
              <div class="item_label">开票名称:</div>
              <el-input v-model="filterData.title" style="width: 100%;" placeholder="货物或服务名称" size="mini"
                clearable></el-input>
            </el-col>


            <el-col style="width: 300px;display: flex;">
              <div class="item_label">销项票备注:</div>
              <el-input v-model="filterData.memo" style="width: 100%;" placeholder="销项票备注" size="mini"
                clearable></el-input>
            </el-col>


            <el-col style="width: 300px;display: flex;">
              <div class="item_label">购方名称:</div>
              <el-select v-model="filterData.buyer" style="width: 100%;" size="mini" placeholder="购方名称" filterable allow-create     clearable>
                <el-option v-for="(item,index) in buyerlist" :label="item.title" :value="item.title" :key="index">
                </el-option>
              </el-select>
            </el-col>





            <el-col style="width: 300px;display: flex;" v-if="false">
              <div class="item_label">销方名称:</div>
              <el-select v-model="filterData.seller" style="width: 100%;" size="mini" placeholder="销方名称" filterable
                clearable>
                <el-option v-for="(item,index) in sellerlist" :label="item.name" :value="item.name" :key="index">
                </el-option>
              </el-select>
            </el-col>

            <el-col style="width: 200px;display: flex;">
              <div class="item_label">进项状态:</div>
              <el-select v-model="filterData.buystatus" placeholder="进项状态" size="mini" clearable style="width: 100%;"
                clearable>
                 <el-option label="完整" value="1"></el-option>
                <el-option label="不完整" value="0"></el-option>
              </el-select>
            </el-col>
              <el-col style="width: 300px;display: flex;">
              <div class="item_label">采购单号:</div>
              <el-input placeholder="关联采购单号" v-model="filterData.bind_buyreqcode" clearable></el-input>
            </el-col>

            <el-col style="width: 300px;display: flex;">
              <div class="item_label">进项发票号:</div>
              <el-input v-model="filterData.buyfphm" style="width: 100%;" placeholder="进项数电票号码或纸质发票号码" size="mini"
                clearable></el-input>
            </el-col>


            <el-col style="width: 300px;display: flex;line-height: 30px;">
              <div class="item_label">所属账套:</div>
              <el-select v-model="filterData.account" filterable placeholder="账套" style="width: 100%;" clearable>
                <el-option :label="item.name" :value="item.name" v-for="(item,index) in accounts"
                  :key="index"></el-option>
              </el-select>
            </el-col>



            <el-col style="width: 200px;display: flex;">
              <el-button type="primary" icon="el-icon-search" @click="currentRow=null;curpage=1;loadDataList()"
                size="mini">查询发票</el-button>
            </el-col>
          </el-row>
        </div>
      </el-row>
    </div>
    <div>
      <div style="text-align: right;">
        <div style="margin-bottom: 5px;">
          <el-popconfirm @confirm="handleExport();" :title="selection.length>0? '确定要导出选中项？ (共'+selection.length+'条）？':'确定要导出全部查询明细（共'+numrows+'条)？'">
            <el-button type="primary" slot="reference" size="mini" icon="el-icon-download" :loading="exporting">
              {{selection.length>0? "导出选中项":"导出全部"}}
            </el-button>
          </el-popconfirm>
        </div>
      </div>

      <div style="height: 320px;">
        <el-table :data="tableData" ref="tickettable" border style="width: 100%;" height="100%" highlight-current-row
          empty-text="暂无发票或未查询到相关发票信息" @select="handleSelection" @select-all="handleSelection"
          @row-click="handleRowClick"
          :header-cell-style="{'background-color': '#f5f7f9','color':'#3e3e3e',border:'1px solid #e5e5e5'}">
          <el-table-column label="" type="selection" align="center" fixed="left" width="50"></el-table-column>
          <el-table-column label="序号" type="index" align="center" fixed="left" width="50"></el-table-column>
          <el-table-column label="状态" prop="status" width="60px" align="center">
            <template v-slot="scope">
              <span v-if="scope.row.status=='1'"
                style="background-color:#00bc00;color:#FFFFFF;padding: 2px 5px;">正常</span>
              <span v-if="scope.row.status=='0'"
                style="background-color:#a5a5a5;color:#FFFFFF;padding: 2px 5px;">作废</span>
              <span v-if="scope.row.status=='2'"
                style="background-color:#ffaa00;color:#FFFFFF;padding: 2px 5px;">红冲</span>
            </template>
          </el-table-column>
          <el-table-column label="开票日期" prop="date" width="140px" align="center"></el-table-column>
          <el-table-column label="类型" prop="type" width="95px" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="购方名称" prop="buyer" width="150px" show-overflow-tooltip></el-table-column>
          <el-table-column label="发票号码" prop="fphm" width="160px" align="center"
            show-overflow-tooltip></el-table-column>
          <el-table-column label="发票代码" prop="fpdm" v-if="false" width="100px" align="center"
            show-overflow-tooltip></el-table-column>
          <el-table-column label="税收分类及名称" prop="title" width="220px" align="left" show-overflow-tooltip>
            <template v-slot="scope">
              *{{scope.row.taxname}}*{{scope.row.title}}
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="model" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="单位" prop="unit" width="60px" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="数量" prop="count" width="80px" align="center"></el-table-column>
          <el-table-column label="单价" prop="price" width="95px" align="center"></el-table-column>
          <el-table-column label="金额" v-if="false" prop="total" width="95px" align="center"></el-table-column>
          <el-table-column label="税额/税率" v-if="false" prop="tax" width="95px" align="center">
            <template v-slot="scope">
              {{scope.row.tax}} ({{scope.row.rate*100}}%)
            </template>
          </el-table-column>
          <el-table-column label="合计" prop="sum" width="95px" align="center"></el-table-column>
          <el-table-column label="开票方名称" prop="seller" width="120px" v-if="false"
            show-overflow-tooltip></el-table-column>
          <el-table-column label="关联进项票" align="center">
            <el-table-column label="进项票额" align="center" prop="buyticket_bindrmb"></el-table-column>
            <el-table-column label="进项票号" width="120px" prop="buyticket_bindnum" align="center"
              show-overflow-tooltip></el-table-column>
            <el-table-column label="状态" align="center" width="85px">
              <template v-slot="scope">
                <div style="cursor: pointer;" @click="handlebind(scope.$index,scope.row)" title="关联进项发票明细">
                  <span v-if="scope.row.buyticket_bindstatus==0" style="color:#FF0000;">不完整</span>
                  <span v-if="scope.row.buyticket_bindstatus==1" style="color:#00bc00">完整</span>
                  <span class="el-icon-info" v-if="scope.row.buyticket_bindstatusmemo!=''" style="cursor: pointer;" :title="'备注:'+scope.row.buyticket_bindstatusmemo"></span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="所属账套" prop="seller" width="150px" align="center"
            show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="100" align="center" fixed="right">
            <template v-slot="scope">
              <el-button-group>
                <el-button size="mini" circle icon="el-icon-edit-outline" title="编辑明细"
                  @click="handleEdit(scope.$index,scope.row)"></el-button>
                <el-button size="mini" icon="el-icon-link" v-if="scope.row.attach.length>0" circle title="查看附件"
                  @click="handlePreviewAttach(scope.$index,scope.row)"></el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="display: flex;">
        <div style="flex: 1;line-height: 35px;">

          <span style="margin-right: 20px;">
            明细总额: {{parseFloat(sumall).toFixed(2)}}
          </span>

          <span style="margin-right: 20px;">
            选中金额: {{parseFloat(sumtotal_selection).toFixed(2)}}
          </span>

          <span style="margin-right: 20px;">
            选中税额: {{parseFloat(sumtax_selection).toFixed(2)}}
          </span>

          <span style="margin-right: 20px;">
            选中价税: {{parseFloat(sumall_selection).toFixed(2)}}
          </span>
        </div>
        <el-pagination layout=" prev, pager,next,sizes,total" :total="numrows" :page-size="pagesize"
          :current-page="curpage" prev-text="上一页" next-text="下一页" :page-sizes="[15, 30, 50]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
      </div>
      <!--底部明细-->
      <div>
        <el-row>
          <el-col :span="12">
            <div class="title">已关联进项明细</div>
            <div style=" height: 260px;">
              <el-table :data="bindlist" border style="height: 100%;" empty-text="暂未绑定进项">
                <el-table-column label="序号" type="index" align="center"></el-table-column>
                <el-table-column label="开票日期" prop="buyticketdate" width="90px" align="center"></el-table-column>
                <el-table-column label="进项发票号" prop="buyticketfphm" show-overflow-tooltip></el-table-column>
                <el-table-column label="发票类型" prop="type" align="center"></el-table-column>
                <el-table-column label="进项名称" show-overflow-tooltip>
                  <template v-slot="scope">
                    *{{scope.row.taxname}}*{{scope.row.title}}
                  </template>
                </el-table-column>
                <el-table-column label="单位" prop="unit" align="center" width="80px"></el-table-column>
                <el-table-column label="数量" prop="count" align="center" width="90px"></el-table-column>
                <el-table-column label="金额" prop="total" align="center" width="90px"></el-table-column>
                <el-table-column label="开票方" prop="seller" align="center" show-overflow-tooltip></el-table-column>
              </el-table>
            </div>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
      </div>
    </div>
    <AttachViewerUI ref="attachUI" v-if="attachVisible" />
    <CreateUI ref="createUI" v-if="createVisible"></CreateUI>
    <BindUI ref="editUI" v-if="editVisible" @updated="handleBindEditCallback"></BindUI>
    <EditUI ref="basicUI" v-if="basicVisible"></EditUI>
  </div>
</template>

<script>
  import {
    Loading
  } from 'element-ui';
  import BindUI from './bind.vue';
  import CreateUI from './create.vue';
  import EditUI from './edit.vue';
  import AttachViewerUI from '@/components/attachviewer.vue'
  export default {
    components: {
      BindUI,
      CreateUI,
      AttachViewerUI,
      EditUI
    },
    data() {
      return {
        buyerlist: [],
        sellerlist: [],
        filterData: {
          daterange: [],
          type: '',
          supname: '',
          num: '',
          model: '',
          code: '',
          sum: '',
          good: '',
          buynums: '',
          saleok: '',
          discard: '',
          memo: ''
        },
        accounts: [],
        sumall: 0,
        basicVisible: false,
        createVisible: false,
        sum_selection: 0,
        sumtax_selection:0,
        sumtotal_selection:0,
        sumall_selection:0,
        editVisible: false,
        attachVisible: false,
        suppliers: [],
        curpage: 1,
        pagesize: 15,
        numrows: 1,
        tableData: [],
        currentRow: null,
        bindlist: [],
        selection: [],
        exporting: false,
      }
    },
    mounted() {
      var now= new Date();
      var firstDay=this.formatDate(new Date(now.getFullYear(),now.getMonth(),1));
      var lastDay=this.formatDate(new Date(now.getFullYear(),now.getMonth()+1,0));
      this.filterData.daterange = [firstDay,lastDay];

      this.loadSellerList();
      this.loadBuyerList();
      this.loadDataList();
      this.loadAccounts();
    },
    methods: {
      formatDate(date) {
        const yyyy = date.getFullYear();
        const mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        const dd = String(date.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
      },
      loadAccounts() {
        this.axios.post("api/admin/account/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.accounts = res.data.list;
          }
        })
      },
      handleRowClick(row, column, event) {
        this.currentRow = row;
        this.bindlist = row.bind_buylist;
      },
      loadBuyerList() {
        this.axios.post("api/admin/client/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.buyerlist = res.data.list;
          }
        });
      },
      loadSellerList() {
        this.axios.post("api/admin/supplier/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.sellerlist = res.data.list;
          }
        });
      },
      handleExport(cmd) {
        if(this.selection.length>0){
           this.handleExportCheck();
        }else{
          this.handleAllExport();
        }
      },
      handleExportCheck() {
        //导出excel
        var index = 1;
        let slist = this.selection.map((item) => {
          let obj = {
            "序号": index,
            "状态": item.status == "1" ? "正常" : "作废",
            "开票日期": item.date,
            "发票类型": item.type,
            "购方名称": item.buyer,
            "发票号码或数电票号码": item.fphm,
            "发票代码": item.fpdm,
            "税收类目名称": item.taxname,
            "货物或服务名称": item.title,
            "规格型号": item.model,
            "单位": item.unit,
            "数量": item.count,
            "单价": item.price,
            "金额": item.total,
            "税率": item.rate,
            "税额": item.tax,
            "价税总额": item.sum,
            "关联进项发票号": item.buyticket_bindnum,
            "关联进项状态": item.buyticket_bindstatus == "0" ? '不完整' : "完整",
            "关联进项金额":item.buyticket_bindrmb,
            "所属账套": item.seller
          }
          index++;
          return obj;
        });
        let ws = XLSX.utils.json_to_sheet(slist, {
          skipHeader: false
        });
        ws["!cols"] = [{
          wpx: 80
        }];
        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, '销项发票明细');
        XLSX.writeFile(wb, "导出销项发票明细" + (this.filterData.seller ? this.filterData.seller : "") + " " + this
          .CurrentDateTime() + ".xlsx");
        loadingInstance.close();
      },
      handleAllExport() {
        this.exporting = true;
        var params = {
          daterange: this.filterData.daterange,
          status: this.filterData.status,
          type: this.filterData.type,
          fphm: this.filterData.fphm,
          title: this.filterData.title,
          buyer: this.filterData.buyer,
          seller: this.filterData.seller,
          buystatus: this.filterData.buystatus,
          account: this.filterData.account,
          buyfphm: this.filterData.buyfphm,
          model: this.filterData.model,
          memo: this.filterData.memo,
          type: this.filterData.type,
          pagesize: this.pagesize
        }
        this.axios.post("api/admin/saleticketdetail/export", params).then((res) => {
          if (res.status == 200 && res.data.code) {
            this.tableData = res.data.list;
            //导出excel
            var index = 1;
            let slist = this.tableData.map((item) => {
              let obj = {
                "序号": index,
                "状态": item.status == "1" ? "正常" : "作废",
                "开票日期": item.date,
                "发票类型": item.type,
                "购方名称": item.buyer,
                "发票号码或数电票号码": item.fphm,
                "发票代码": item.fpdm,
                "税收类目名称": item.taxname,
                "货物或服务名称": item.title,
                "规格型号": item.model,
                "单位": item.unit,
                "数量": item.count,
                "单价": item.price,
                "金额": item.total,
                "税率": item.rate,
                "税额": item.tax,
                "价税总额": item.sum,
                "关联进项发票号": item.buyticket_bindnum,
                "关联进项状态": item.buyticket_bindstatus == "0" ? '不完整' : "完整",
                "关联进项金额":item.buyticket_bindrmb,
                "所属账套": item.seller
              }
              index++;
              return obj;
            })
            let ws = XLSX.utils.json_to_sheet(slist, {
              skipHeader: false
            });
            ws["!cols"] = [{
              wpx: 80
            }];
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, '销项发票明细');
            XLSX.writeFile(wb, "导出销项发票明细" + (this.filterData.seller ? this.filterData.seller : "") + " " + this
              .CurrentDateTime() + ".xlsx");
            this.exporting = false;
          }
        });
      },
      handlePreviewAttach(index, data) {
        this.attachVisible = true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.initData(JSON.parse(JSON.stringify(data.attach)));
        })
      },
      handleSelection(list) {
        this.sum_selection = 0;
        this.selection = list;
        this.sumtax_selection=0;
        this.sumtotal_selection=0;
        this.sumall_selection=0;
        list.forEach(item => {
          this.sum_selection += parseFloat(item.sum);
          this.sumtax_selection+=parseFloat(item.tax);
          this.sumtotal_selection+=parseFloat(item.total);
          this.sumall_selection+=parseFloat(item.sum);

        })
      },
      handleEdit(index, data) {
        this.basicVisible = true;
        this.$nextTick(() => {
          this.$refs.basicUI.dialogVisible = true;
          this.$refs.basicUI.init(index, JSON.parse(JSON.stringify(data)));
        })
      },
      handlebind(index, data) {
        this.editVisible = true;
        this.$nextTick(() => {
          this.$refs.editUI.dialogVisible = true;
          this.$refs.editUI.initData(index, JSON.parse(JSON.stringify(data)));
        })
      },
      handleBindEditCallback(index, data) {
        console.log(data);
        this.tableData[index].buyticket_bindrmb=data.buyticket_bindrmb;
        this.tableData[index].buyticket_bindnum = data.buyticket_bindnum;
        this.tableData[index].buyticket_bindstatus = data.buyticket_bindstatus;
        this.tableData[index].buyticket_bindstatusmemo = data.buyticket_bindstatusmemo;
      },
      handleSearch() {
        this.curpage = 1;
        this.loadDataList();
      },
      loadSuppliers() {
        this.axios.post("api/sup/buysupplier/list_item").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.suppliers = res.data.list;
          }
        });
      },
      handleSizeChange: function(val) {
        this.pagesize = val;
        this.curpage = 1;
        this.loadDataList();
      },
      handleCurrentChange: function(val) {
        this.curpage = parseInt(val);
        this.loadDataList();
      },
      loadDataList() {
        var params = {
          daterange: this.filterData.daterange,
          status: this.filterData.status,
          type: this.filterData.type,
          fphm: this.filterData.fphm,
          title: this.filterData.title,
          buyer: this.filterData.buyer,
          seller: this.filterData.seller,
          buystatus: this.filterData.buystatus,
          account: this.filterData.account,
          buyfphm: this.filterData.buyfphm,
          model: this.filterData.model,
          memo: this.filterData.memo,
          curpage: this.curpage,
          type: this.filterData.type,
          pagesize: this.pagesize
        }
        this.axios.post("api/admin/saleticketdetail/list_by_page", params).then((res) => {
          if (res.status == 200 && res.data.code) {
            this.tableData = res.data.list;
            this.numrows = res.data.numrows;
            this.sumall = res.data.sumall;
          }
        });
      },
      handleViewAttach() {
        this.attachVisible = true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.init(JSON.parse(JSON.stringify(this.currentRow.attach)));
        })
      },
      handleEditCallback(index, data) {
        this.tableData[index].goods = data.goods;
        this.tableData[index].sum = data.sum;
        this.tableData[index].total = data.total;
        this.tableData[index].num = data.num;
        this.tableData[index].type = data.type;
        this.tableData[index].date = data.date;
        this.tableData[index].supname = data.supname;
        this.tableData[index].code = data.code;
        this.tableData[index].tax = data.tax;
        this.tableData[index].memo = data.memo;
        this.tableData[index].attach = data.attach;
        this.list = this.tableData[index].attach;
        if (this.list.length > 0) {
          this.cur = 0;
          this.curdata = this.list[this.cur];
        } else {
          this.cur = -1;
          this.curdata = {
            type: '-1',
            url: '',
            attach: []
          };
        }

      },
      handleCreate() {
        this.createVisible = true;
        this.$nextTick(() => {
          this.$refs.createUI.dialogVisible = true;
          this.$refs.createUI.initData();
        })
      },
      handleSelect(index) {
        this.cur = index;
        this.curdata = {};
        this.curdata = this.list[this.cur];
      }
    }
  }
</script>

<style scoped>
  .item_label {
    text-align: center;
    line-height: 35px;
    margin: 0px 2px;
    width: 95px;
  }

  .title {
    position: relative;
    padding-left: 10px;
    margin-bottom: 15px;
    font-size: 14px;
    color: #333;
    font-weight: 700;
  }

  .title:before {
    content: "";
    position: absolute;
    top: 4px;
    left: 0;
    width: 5px;
    height: 65%;
    background-color: #249af3;
  }

  .table-wraper {
    height: calc(100vh - 240px);
  }

  .el-select .el-input {
    width: 230px;
  }

  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
</style>
